package com.eig.system.service.impl;


import com.eig.common.entity.AclPermission;
import com.eig.common.util.JWTUtil;
import com.eig.common.vo.Result;
import com.eig.security.utils.WebUtils;
import com.eig.system.dao.AclPermissionDao;
import com.eig.system.service.AclPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @program: eight-education-cloud
 * @description:
 * @author:
 * @create:
 **/
@Service
public class AclPermissionServiceImpl implements AclPermissionService {

    @Autowired
    private AclPermissionDao permissionDao;
    @Override
    public Result findByUserId(Long userid) {
        List<AclPermission> aclPermissions = permissionDao.selectByUserid(userid);
        return new Result<List<AclPermission>>(2000,"查询成功",aclPermissions);
    }

    @Override
    public Result<List<AclPermission>> findByUsername() {
        //1.得到当前用户的名称
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> map = JWTUtil.getTokenChaim(token);
        String username = (String) map.get("username");

        //2.调用dao中根据用户名查询该用户具有的菜单。
        List<AclPermission> permissions = permissionDao.selectByUsername(username);


        //1. 查询一级菜单
        List<AclPermission> first=new ArrayList<>();
        for(AclPermission permission:permissions){
              if(permission.getPid()==1){
                   first.add(permission);
              }
        }
        //2. 查询一级菜单下的子菜单
        for(AclPermission f:first){
             f.setChildren(findChildren(permissions,f.getId()));
        }
        return new Result<>(2000,"查询左侧菜单成功",first);
    }
    //3.方法的递归
    private List<AclPermission> findChildren(List<AclPermission> permissions, Long id) {
           List<AclPermission> seconds=new ArrayList<>();
           for(AclPermission p:permissions){
                 if(p.getPid().equals(id)){
                      seconds.add(p);
                 }
           }

           for(AclPermission p :seconds){
                 p.setChildren(findChildren(permissions,p.getId()));
           }
           return seconds;
    }


}












